package com.apy.accountbook

import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.apy.accountbook.model.AppDatabase
import com.apy.accountbook.model.Bill
import kotlinx.coroutines.runBlocking
import java.text.SimpleDateFormat
import java.util.Locale

class WidgetService : RemoteViewsService() {
    override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
        return WidgetViewsFactory(applicationContext, intent)
    }
}

class WidgetViewsFactory(
    private val context: Context,
    private val intent: Intent
) : RemoteViewsService.RemoteViewsFactory {

    private val bills = mutableListOf<Bill>()

    override fun onCreate() {
        // 初始化数据
    }

    override fun onDataSetChanged() {
        // 使用 runBlocking 调用挂起函数
        Log.e("WidgetService","onDataSetChanged")
        runBlocking {
            val database = AppDatabase.getDatabase(context)
            bills.clear()
            bills.addAll(database.billDao().getTodayBills())
        }
    }

    override fun onDestroy() {
        // 清理资源
    }

    override fun getCount(): Int {
        return bills.size
    }

    override fun getViewAt(position: Int): RemoteViews {
        val bill = bills[position]
        val dateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())

        val views = RemoteViews(context.packageName, R.layout.widget_item)
        views.setTextViewText(R.id.tv_amount, bill.money.toString())
        views.setTextViewText(R.id.tv_note, bill.mark)
        views.setTextViewText(R.id.tv_date, dateFormat.format(bill.create_at))
        return views
    }

    override fun getLoadingView(): RemoteViews? {
        return null
    }

    override fun getViewTypeCount(): Int {
        return 1
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun hasStableIds(): Boolean {
        return true
    }
}